package com.stone.mythread.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {

    public static void main(String[] args) {
        demo03();
    }

    public static void demo01() {
        // 一池五线程
        ExecutorService executor = Executors.newFixedThreadPool(5); // 类似银行五个窗口

        try {
            // 10 个顾客请求
            for (int i = 1; i <= 10; i++) {
                // 执行
                int finalI = i;
                executor.execute(() -> {
                    System.err.println(Thread.currentThread().getName() + " 办理用户 " + finalI + "的业务 ");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } finally {
            // 放回线程池
            executor.shutdown();
        }
    }


    public static void demo02() {
        // 一池一线程
        ExecutorService executor = Executors.newSingleThreadExecutor(); // 类似银行一个窗口

        try {
            // 10 个顾客请求
            for (int i = 1; i <= 10; i++) {
                // 执行
                int finalI = i;
                executor.execute(() -> {
                    System.err.println(Thread.currentThread().getName() + " 办理用户 " + finalI + "的业务 ");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } finally {
            // 放回线程池
            executor.shutdown();
        }
    }


    public static void demo03() {
        // 一池可扩容线程
        ExecutorService executor = Executors.newCachedThreadPool();

        try {
            // 10 个顾客请求
            for (int i = 1; i <= 10; i++) {
                // 执行
                int finalI = i;
                executor.execute(() -> {
                    System.err.println(Thread.currentThread().getName() + " 办理用户 " + finalI + "的业务 ");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } finally {
            // 放回线程池
            executor.shutdown();
        }
    }
}
